<?php
/**
 * Track Members Info
 * 
 * @name		track members info
 * @version		1.1
 * @package		nats-space
 * @see			http://code.google.com/p/nats-space/
 * @copyright	2008-2009
 * @author		Joseph C. <joseph.cheys@gmail.com>
 */
class Nats3space_Members
{
	/**
	 * Get error message from here if method
	 *  
	 * @var string - Last error message 
	 */
	protected static $error_msg;
	
	/**
	 * Track login
	 * See details here: http://wiki.toomuchmedia.com/index.php/Member_Logging
	 * 
	 * @param string $natsUrl - the url to NATS affiliate tracking system
	 * @param string $userName - members name
	 * @param string $remoteAddr - members remote IP address
	 * @param string $siteIds - coma separated site IDs mmeber is login to
	 * @return boolean - return true on success open
	 */
	public static function TrackLogin($natsUrl, $userName, $remoteAddr, $siteIds = null)
	{
		// validate required values to avoid the unpredictable 
		// results in NATs membership login statistics
		if (empty($natsUrl)) {
			self::$error_msg = 'NATS affiliate tracking system URL is empty';
			return false;
		}

		if (empty($userName)) {
			self::$error_msg = 'Members username is empty';
			return false;
		}
		
		if (empty($remoteAddr)) {
			self::$error_msg = 'Remote IP address is empty';
			return false;
		}

		// TODO: validate the $natsUrl to be valid website URL like 'http://www.example.com/'
		
		// Build redirect URL
		
		// TODO: check for the trailing slash in $natsUrl 
		$redirectUrl = $natsUrl . 'special/loginlog.php';
		
		// Add username
		$redirectUrl .= '?username=' . urlencode($userName);
		
		// Add site ID(s)
		if (null === $siteIds) {
			$redirectUrl .= '&nosite=1';
		} elseif (false === strpos($siteIds, ',')) {
			$redirectUrl .= '&siteid=' . urlencode($siteIds); 
		} else {
			$redirectUrl .= '&siteids=' . urlencode($siteIds);
		}
		
		// Track members remote IP address
		$redirectUrl .= '&ip=' . urlencode($remoteAddr);
		
		// Send the request by opening URL as a file 
		// (check "allow_url_fopen" php.ini directive to enable this)
		// TODO: avoid the dependency to 'allow_url_fopen' directive
		$res = file($redirectUrl);

		// process the result
		if (false === $res) {
			self::$error_msg = 'Can\'t connect to: '.$redirectUrl;
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Returns the last error message
	 * 
	 * @return string - Error message
	 */
	public static function getLastErrorMsg()
	{
		return self::$error_msg;
	}

}